﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using Newtonsoft.Json;
using HY.Web.Models;

namespace HY.Web
{
    /// <summary>
    /// 自定义某些类型的返回响应
    /// </summary>
    public class CustomAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
    {
        private readonly AuthorizationMiddlewareResultHandler DefaultHandler = new();
        public async Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
        {
            if (!authorizeResult.Succeeded)
            {
                //处理Ajax请求未授权的情况，如不处理，则服务器默认响应403
                string requestType = context.Request.Headers["X-Requested-With"];
                if (!string.IsNullOrEmpty(requestType) && requestType.Equals("XMLHttpRequest", StringComparison.CurrentCultureIgnoreCase))
                {
                    //context.Response.StatusCode = StatusCodes.Status200OK;
                    ReturnModel returnModel = new()
                    {
                        Code = StatusCodes.Status403Forbidden,
                        Message = "对不起，您暂无足够的权限执行此操作"
                    };
                    context.Response.ContentType = "application/json;charset=utf-8";
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(returnModel));
                    return;
                }
            }
            //正常处理别的请求
            await DefaultHandler.HandleAsync(next, context, policy, authorizeResult);
        }
    }
}
